package zhipu

import (
	"errors"
	jwt "github.com/dgrijalva/jwt-go"
	"strings"
	"time"
)

func ConvKeyToToken(key string) (string, error) {
	keys_arr := strings.Split(key, ".")
	if len(keys_arr) < 2 {
		return "", errors.New(CONST_COMPANY + "-ChatGLM key is not valid")
	}
	type MyCustomClaims struct {
		ApiKey    string `json:"api_key"`
		Timestamp int64  `json:"timestamp"`
		jwt.StandardClaims
	}

	// Create the Claims
	claims := MyCustomClaims{
		ApiKey:    keys_arr[0],
		Timestamp: time.Now().Unix() * 1000,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix()*1000 + 365*24*86400*1000,
			//Issuer:    "test",
		},
	}
	token := &jwt.Token{
		Header: map[string]interface{}{
			//"typ":       "JWT",
			"sign_type": "SIGN",
			"alg":       jwt.SigningMethodHS256.Alg(),
		},
		Claims: claims,
		Method: jwt.SigningMethodHS256,
	}
	//token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tok, err := token.SignedString([]byte(keys_arr[1]))
	if err == nil {
		return tok, nil
	}
	return "", err
}
